#!/usr/bin/env bash

__rvm_if_sudo()
{
  \typeset -a __command
  __command=()
  (( UID == 0 )) || __command+=( \command \sudo -p "%p password required for '$*': " )
  __command+=( $@ )
  "${__command[@]}" || return $?
}

__rvm_fix_permissions_fix_rights()
{
  case "${__user}" in
    (*:*)
      rvm_log "Fixing rights with 'g+w' - this might take a few long minutes..."
      __rvm_if_sudo chmod -R g+w "${rvm_path}" || return $?
      ;;
  esac
}

__rvm_fix_permissions_fix_directories()
{
  \typeset -a __broken_dirs
  \typeset __broken_dir

  while
    __rvm_read_lines __broken_dirs <(
      find "${rvm_path}" -type d -not -perm -111 2>/dev/null || true
    ) &&
    (( ${#__broken_dirs[@]} ))
  do
    for __broken_dir in "${__broken_dirs[@]}"
    do chmod +x "${__broken_dir}" || return $?
    done
  done
}

__rvm_fix_permissions_fix_message()
{
  \typeset __type
  case "${__user}" in
    (:*)  __type="group"      ;;
    (*:*) __type="user/group" ;;
    (*)   __type="user"       ;;
  esac
  rvm_log "Fixing ${__type} for ${__user} - this might take a few long minutes..."
}

__rvm_fix_permissions_fix()
{
  __rvm_fix_permissions_fix_message
  __rvm_if_sudo chown -R "${__user}" "${rvm_path}" &&
  __rvm_fix_permissions_fix_rights &&
  rvm_log "Finished fixing." ||
  {
    \typeset __result=$?
    rvm_error "Failed fixing, read the above messages."
    return ${__result}
  }
}

__rvm_fix_permissions_select()
{
  case "${__user}" in
    ("")
      if (( ${rvm_user_install_flag:=0} == 0 ))
      then __user="system"
      else __user="user"
      fi
      ;;
  esac
  case "${__user}" in
    (system)
      __user=":${rvm_group_name:-rvm}"
      ;;
    (user)
      __user="$USER"
      ;;
  esac
}

__rvm_fix_permissions()
{
  \typeset __user="${1:-}"
  __rvm_fix_permissions_select &&
  __rvm_fix_permissions_fix    &&
  __rvm_fix_permissions_fix_directories ||
  return $?
}

__rvm_fix_permissions "${args[@]}"
